package com.kx.yooli.kx.wechat.utils.date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author john_sqwen-childe.wen
 * date 2024/4/8
 * PROJECT_NAME wechat
 * description create DateUtil by john_sqwen
 * and  value is
 */
public class DateUtil {
    private final Logger log = LoggerFactory.getLogger(DateUtil.class);

    /**
     * 日期转换成字符串
     *
     * @param date
     * @return str
     */
    public static String DateToStr(Date date, String format) {

        SimpleDateFormat sformat = new SimpleDateFormat(format);
        String str = sformat.format(date);
        return str;
    }

    /**
     * 日期转换成字符串
     *
     * @param date
     * @return str
     */
    public static String DateToStr(Date date) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        return str;
    }
    public static String Date2Str(Date date) {

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String str = format.format(date);
        return str;
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return date;
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str, String format) throws Exception {

        SimpleDateFormat sformat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sformat.parse(str);
        } catch (ParseException e) {

            e.printStackTrace();
            throw e;
        }
        return date;
    }

    /**
     * 日期增减计算
     *
     * @param dateString
     * @param add
     *            整数往后推,负数往前移动
     * @return
     * @throws ParseException
     */
    public static String getDateStringAdd(String dateString, int add)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = formatter.parse(dateString);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, add);
        date = calendar.getTime();
        String dateToString = formatter.format(date);
        return dateToString;
    }
    /**
     * 日期增减计算
     *
     * @param dateString
     * @param add
     *            整数往后推,负数往前移动
     * @return
     * @throws ParseException
     */
    public static String getDateStringAdd(Date date, int add)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, add);
        date = calendar.getTime();
        String dateToString = formatter.format(date);
        return dateToString;
    }

    /**
     * 获取当前月第一天 如果是2015年10月
     *
     * @return 2015-10-01
     * @throws ParseException
     */
    public static String getMonthFristDay() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        // 设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
    }

    /**
     * 获取当前月最后一天 如果是2015年10月
     *
     * @return 2015-10-31
     * @throws ParseException
     */
    public static String getMonthLastDay() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = format.format(c.getTime());
        return last;
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime
     *            修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    /**
     * 计算日期差的天数
     *
     * @param beginDateString
     * @param endDateString
     * @return
     * @throws ParseException
     */
    public static long dateMinus(String beginDateString, String endDateString)
            throws ParseException {
        long minusDay = 0;
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date beginDate = dfs.parse(beginDateString);
        java.util.Date endDate = dfs.parse(endDateString);
        minusDay = (endDate.getTime() - beginDate.getTime()) / 1000 / 60 / 60
                / 24;
        return minusDay;
    }



    /**
     * 计算日期差的天数
     *
     * @param beginDateString
     * @param endDateString
     * @return
     * @throws ParseException
     */
    public static long dateMinus(Date beginDate, Date endDate)
            throws ParseException {
        return dateMinus(DateToStr(beginDate),DateToStr(endDate));
    }

    /**
     * 两个日期之间的小时差
     * @param beginDate
     * @param endDate
     * @return
     */
    public static long hourMinus(Date beginDate, Date endDate){
        long hours = (endDate.getTime() - beginDate.getTime()) / 1000 / 60 / 60 ;
        if (hours < 0){
            hours = -hours;
        }
        return hours;
    }

//	public static void main(String[] args) throws ParseException, Exception {
//		System.out.println(dateMinus(StrToDate("2017-04-21","yyyy-MM-dd"),new Date()));
//	}

    /**
     * 月份期增减计算
     *
     * @param MonthString
     *            '2015-01-01'
     * @param add
     *            2
     * @return 2015-03
     * @throws ParseException
     */
    public static String getMonthStringAdd(String MonthString, int add)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Date date = formatter.parse(MonthString);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, add);// 整数往后推,负数往前移动
        date = calendar.getTime();
        String dateToString = formatter.format(date);
        return dateToString;
    }

    /**
     * 计算月份差
     *
     * @param beginMonthString
     *            "2015-01-02",
     * @param endMonthString
     *            "2015-05-01"
     * @return 4
     * @throws ParseException
     */
    public static long dateMonths(String beginMonthString,
                                  String endMonthString) throws ParseException {
        long minusDay = 0;
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM");
        java.util.Date beginDate = dfs.parse(beginMonthString);
        java.util.Date endDate = dfs.parse(endMonthString);
        minusDay = (endDate.getTime() - beginDate.getTime()) / 1000 / 60 / 60
                / 24 / 30;
        return minusDay;
    }
    /**
     * 得到两个日期之间所有日期
     * @param date1
     * @param date2
     * @return
     */
    public static List<String> process(String date1, String date2){
        String dateFormat = "yyyy-MM-dd";
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        List<String> dates = new ArrayList<String>();

        dates.add(date1);//将默认日期加入list
        if(date1.equals(date2)){
            return dates;
        }
        String tmp;
        if(date1.compareTo(date2) >= 0){//确保 date1的日期不晚于date2
            tmp = date1;
            date1 = date2;
            date2 = tmp;
        }

        tmp = format.format(str2Date(date1).getTime() + 3600*24*1000);

        int num = 0;
        while(tmp.compareTo(date2) <= 0){
            dates.add(tmp);
            num++;
            tmp = format.format(str2Date(tmp).getTime() + 3600*24*1000);
        }

        if(num == 0){
        }
        return dates;
    }
    public static Date str2Date(String str) {
        String dateFormat = "yyyy-MM-dd";
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        if (str == null) {
            return null;
        }
        try {
            return format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //还剩几天
    public static String getDates(String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date();
        String dd = sdf.format(date).substring(0, 11) + "23:59:59";
        StringBuilder sb = new StringBuilder();
        Date parse = null;

        try {
            parse = sdf.parse(dd);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long sub = parse.getTime();

        long num = Long.parseLong(str);
        long day = (num - sub)/(24*60*60*1000);
        if(day < 0){
            sb.append("逾期").append(Math.abs(day)).append("天");
        }else if(0 == day){
            sb.append("");
        }else{
            sb.append("剩余").append(day).append("天");
        }
        return sb.toString();
    }

    //应还款日期转换函数
    public static String repayDay(String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(Long.parseLong(str));
        return sdf.format(date);
    }

    //截取年月出来计算
    public static String getYearMonth(String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date date = new Date(Long.parseLong(str));
        Date parse = null;
        try {
            parse = sdf.parse(sdf.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return String.valueOf(parse.getTime());
    }

    //计算时间并加上汉字符
    public static String getYearMonthCN(String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        Date date = new Date(Long.parseLong(str));
        return sdf.format(date);
    }

    //截取年月出来计算
    public static String getYearMonthDate(String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(Long.parseLong(str));
        return sdf.format(date);
    }

    //保留兩位小數
    public static String getTwoNum(Double num){
        //java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        return String.format("%.2f", num);
    }

    //还款日yyyy/MM/dd这个格式的
    public static String getPayDayFormat(String day){
        StringBuilder sb = new StringBuilder();
        sb.append(day.substring(0, 4)).append("/").append(day.substring(4, 6)).append("/").append(day.substring(6, 8));
        return sb.toString();
    }

    //截出多少期的函数，中间用-代替
    public static String subString(String str){
        StringBuilder sb = new StringBuilder();
        String[] split = str.split(",");
        if(split.length > 3){
            return sb.append(split[0]).append("-").append(split[split.length-1]).toString();
        }else{
            return str;
        }
    }
    /**
     * 时间计算
     * @Description (根据当前时间+多少分钟)
     * @param date
     * @param mins
     * @param format
     * @return返回时间
     */
    public static String getToTimesDate(Date date, long mins, String format){
        long curren = date.getTime();
        curren += mins * 60 * 1000;
        Date da = new Date(curren);
        return DateToStr(da, format);
    }

    /**
     * 获取当前时间(年月日 2017年08月08日)
     * @return
     */
    public static String getCurrentDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(new Date());
    }

    public static Integer getAgeByIdCard(String idCard) {
        int leh = idCard.length();
        String dates = "";
        if (leh == 18) {
            int birYear = Integer.parseInt(idCard.substring(6, 10));
            int birMonth = Integer.parseInt(idCard.substring(10, 12));
            int birDay = Integer.parseInt(idCard.substring(12, 14));
            GregorianCalendar currentDay = new GregorianCalendar();
            int year = currentDay.get(Calendar.YEAR);
            int month = currentDay.get(Calendar.MONTH) + 1;
            int day = currentDay.get(Calendar.DAY_OF_MONTH);
            if (birMonth > month)
                birYear++;
            else if (birMonth == month && birDay > day)
                birYear++;

            return year - birYear;
        } else {
            dates = idCard.substring(6, 8);
            return Integer.parseInt(dates);
        }
    }
}
